package my.common;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;


public abstract class BaseController {
	Log log = LogFactory.getLog(BaseController.class);
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;

	// 页面表单存放数据
	protected Map<String, String> paramMap = new HashMap<String, String>();

	/**
	 * 以MAP的格式，接收所有参数
	 * @return
	 */
	protected Map<String, String> getRequestMap() {
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<String> enumeration = this.request.getParameterNames();
		while (enumeration.hasMoreElements()) {
			String name = enumeration.nextElement();
			map.put(name, request.getParameter(name));
		}
		return map;
	}
	/**
	 * 数据流类型输出
	 * @param str
	 */
	public void toWrite(String str) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter pw = null;
			pw = response.getWriter();
			pw.write(str);
			pw.flush();
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * JOSN类型输出
	 * @param obj
	 */
	protected void writeJson(Object obj) {
		String jsonString = JSON.toJSONString(obj); 
		log.info("json输出数据==>" + jsonString);
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/x-json;charset=UTF-8");
			PrintWriter pw = null;
			pw = response.getWriter();
			pw.write(jsonString);
			pw.flush();
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
 
 
	public Map<String, String> getParamMap() {
		return paramMap;
	}

	public void setParamMap(Map<String, String> paramMap) {
		this.paramMap = paramMap;
	}

}